package com.zenithmind.task.controller;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.task.pojo.entity.Task;
import com.zenithmind.task.pojo.query.TaskQuery;
import com.zenithmind.task.pojo.vo.TaskVO;
import com.zenithmind.task.service.TaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 任务管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/task")
@RequiredArgsConstructor
@Tag(name = "任务管理", description = "任务的创建、编辑、分配、跟踪等功能")
public class TaskController {

    private final TaskService taskService;

    // ==================== 基础CRUD操作 ====================

    @GetMapping("/page")
    @Operation(summary = "分页查询任务列表", description = "支持多条件筛选的任务分页查询")
    public Result<PageResult<TaskVO>> getTaskPage(TaskQuery query) {
        String userId = UserContext.requireUserId();
        PageResult<TaskVO> result = taskService.getTaskPage(query, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询任务详情", description = "根据ID查询任务的详细信息")
    public Result<TaskVO> getTaskById(@Parameter(description = "任务ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        TaskVO task = taskService.getTaskById(id, userId);
        return Result.success(task);
    }

    @PostMapping
    @Operation(summary = "创建任务", description = "创建新的任务")
    public Result<Boolean> createTask(@Valid @RequestBody Task task) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.createTask(task, userId);
        return Result.success(result);
    }

    @PutMapping
    @Operation(summary = "更新任务", description = "更新任务信息")
    public Result<Boolean> updateTask(@Valid @RequestBody Task task) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.updateTask(task, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除任务", description = "删除指定的任务")
    public Result<Boolean> deleteTask(@Parameter(description = "任务ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.deleteTask(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除任务", description = "批量删除多个任务")
    public Result<Boolean> batchDeleteTasks(@RequestBody List<String> ids) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.batchDeleteTasks(ids, userId);
        return Result.success(result);
    }

    // ==================== 任务状态管理 ====================

    @PutMapping("/{id}/status")
    @Operation(summary = "更新任务状态", description = "更新任务的状态")
    public Result<Boolean> updateTaskStatus(
            @Parameter(description = "任务ID") @PathVariable String id,
            @Parameter(description = "新状态") @RequestParam Integer status,
            @Parameter(description = "备注") @RequestParam(required = false) String remark) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.updateTaskStatus(id, status, userId, remark);
        return Result.success(result);
    }

    @PutMapping("/{id}/start")
    @Operation(summary = "开始任务", description = "将任务状态设置为进行中")
    public Result<Boolean> startTask(@Parameter(description = "任务ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.startTask(id, userId);
        return Result.success(result);
    }

    @PutMapping("/{id}/complete")
    @Operation(summary = "完成任务", description = "将任务标记为已完成")
    public Result<Boolean> completeTask(
            @Parameter(description = "任务ID") @PathVariable String id,
            @Parameter(description = "实际工时") @RequestParam(required = false) Double actualHours,
            @Parameter(description = "完成说明") @RequestParam(required = false) String completionNote) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.completeTask(id, userId, actualHours, completionNote);
        return Result.success(result);
    }

    @PutMapping("/{id}/pause")
    @Operation(summary = "暂停任务", description = "将任务状态设置为暂停")
    public Result<Boolean> pauseTask(
            @Parameter(description = "任务ID") @PathVariable String id,
            @Parameter(description = "暂停原因") @RequestParam(required = false) String reason) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.pauseTask(id, userId, reason);
        return Result.success(result);
    }

    @PutMapping("/{id}/cancel")
    @Operation(summary = "取消任务", description = "将任务状态设置为已取消")
    public Result<Boolean> cancelTask(
            @Parameter(description = "任务ID") @PathVariable String id,
            @Parameter(description = "取消原因") @RequestParam(required = false) String reason) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.cancelTask(id, userId, reason);
        return Result.success(result);
    }

    // ==================== 任务分配管理 ====================

    @PostMapping("/{taskId}/assign")
    @Operation(summary = "分配任务", description = "将任务分配给指定用户")
    public Result<Boolean> assignTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "被分配人ID") @RequestParam String assigneeId,
            @Parameter(description = "分配类型") @RequestParam(defaultValue = "1") Integer assignmentType,
            @Parameter(description = "角色权限") @RequestParam(defaultValue = "2") Integer rolePermission,
            @Parameter(description = "分配说明") @RequestParam(required = false) String note) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.assignTask(taskId, assigneeId, assignmentType, rolePermission, note, userId);
        return Result.success(result);
    }

    @PostMapping("/{taskId}/assign/batch")
    @Operation(summary = "批量分配任务", description = "将任务批量分配给多个用户")
    public Result<Boolean> batchAssignTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "被分配人ID列表") @RequestBody List<String> assigneeIds,
            @Parameter(description = "分配类型") @RequestParam(defaultValue = "2") Integer assignmentType) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.batchAssignTask(taskId, assigneeIds, assignmentType, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{taskId}/assign/{assigneeId}")
    @Operation(summary = "取消任务分配", description = "取消任务的分配")
    public Result<Boolean> unassignTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "被分配人ID") @PathVariable String assigneeId) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.unassignTask(taskId, assigneeId, userId);
        return Result.success(result);
    }

    @PutMapping("/assignment/{assignmentId}/accept")
    @Operation(summary = "接受任务分配", description = "接受分配给自己的任务")
    public Result<Boolean> acceptAssignment(@Parameter(description = "分配ID") @PathVariable String assignmentId) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.acceptAssignment(assignmentId, userId);
        return Result.success(result);
    }

    @PutMapping("/assignment/{assignmentId}/reject")
    @Operation(summary = "拒绝任务分配", description = "拒绝分配给自己的任务")
    public Result<Boolean> rejectAssignment(
            @Parameter(description = "分配ID") @PathVariable String assignmentId,
            @Parameter(description = "拒绝原因") @RequestParam String reason) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.rejectAssignment(assignmentId, reason, userId);
        return Result.success(result);
    }

    // ==================== 任务进度管理 ====================

    @PutMapping("/{id}/progress")
    @Operation(summary = "更新任务进度", description = "更新任务的完成进度")
    public Result<Boolean> updateTaskProgress(
            @Parameter(description = "任务ID") @PathVariable String id,
            @Parameter(description = "进度百分比") @RequestParam Integer progress,
            @Parameter(description = "进度说明") @RequestParam(required = false) String note) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.updateTaskProgress(id, progress, userId, note);
        return Result.success(result);
    }

    @PostMapping("/{id}/work-hours")
    @Operation(summary = "记录工时", description = "记录任务的工作时间")
    public Result<Boolean> logWorkHours(
            @Parameter(description = "任务ID") @PathVariable String id,
            @Parameter(description = "工时") @RequestParam Double hours,
            @Parameter(description = "工作描述") @RequestParam(required = false) String description) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.logWorkHours(id, hours, description, userId);
        return Result.success(result);
    }

    // ==================== 任务关注管理 ====================

    @PostMapping("/{taskId}/follow")
    @Operation(summary = "关注任务", description = "关注指定的任务")
    public Result<Boolean> followTask(@Parameter(description = "任务ID") @PathVariable String taskId) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.followTask(taskId, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{taskId}/follow")
    @Operation(summary = "取消关注任务", description = "取消关注指定的任务")
    public Result<Boolean> unfollowTask(@Parameter(description = "任务ID") @PathVariable String taskId) {
        String userId = UserContext.requireUserId();
        Boolean result = taskService.unfollowTask(taskId, userId);
        return Result.success(result);
    }

    // ==================== 任务查询方法 ====================

    @GetMapping("/my")
    @Operation(summary = "查询我的任务", description = "查询分配给当前用户的任务")
    public Result<PageResult<TaskVO>> getMyTasks(TaskQuery query) {
        String userId = UserContext.requireUserId();
        PageResult<TaskVO> result = taskService.getMyTasks(query, userId);
        return Result.success(result);
    }

    @GetMapping("/my/created")
    @Operation(summary = "查询我创建的任务", description = "查询当前用户创建的任务")
    public Result<PageResult<TaskVO>> getMyCreatedTasks(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        String userId = UserContext.requireUserId();
        PageResult<TaskVO> result = taskService.getMyCreatedTasks(userId, pageNum, pageSize);
        return Result.success(result);
    }

    @GetMapping("/my/followed")
    @Operation(summary = "查询我关注的任务", description = "查询当前用户关注的任务")
    public Result<PageResult<TaskVO>> getMyFollowedTasks(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        String userId = UserContext.requireUserId();
        PageResult<TaskVO> result = taskService.getMyFollowedTasks(userId, pageNum, pageSize);
        return Result.success(result);
    }

    @GetMapping("/overdue")
    @Operation(summary = "查询逾期任务", description = "查询当前用户的逾期任务")
    public Result<PageResult<TaskVO>> getOverdueTasks(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        String userId = UserContext.requireUserId();
        PageResult<TaskVO> result = taskService.getOverdueTasks(userId, pageNum, pageSize);
        return Result.success(result);
    }

    @GetMapping("/today")
    @Operation(summary = "查询今日任务", description = "查询当前用户今天的任务")
    public Result<List<TaskVO>> getTodayTasks() {
        String userId = UserContext.requireUserId();
        List<TaskVO> result = taskService.getTodayTasks(userId);
        return Result.success(result);
    }

    @GetMapping("/week")
    @Operation(summary = "查询本周任务", description = "查询当前用户本周的任务")
    public Result<List<TaskVO>> getWeekTasks() {
        String userId = UserContext.requireUserId();
        List<TaskVO> result = taskService.getWeekTasks(userId);
        return Result.success(result);
    }

    // ==================== 任务统计方法 ====================

    @GetMapping("/statistics")
    @Operation(summary = "获取任务统计", description = "获取任务的统计信息")
    public Result<Map<String, Object>> getTaskStatistics(
            @Parameter(description = "项目ID") @RequestParam(required = false) String projectId,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        String userId = UserContext.requireUserId();
        Map<String, Object> result = taskService.getTaskStatistics(userId, projectId, startTime, endTime);
        return Result.success(result);
    }

    @GetMapping("/statistics/completion-trend")
    @Operation(summary = "获取任务完成趋势", description = "获取指定天数内的任务完成趋势")
    public Result<List<Map<String, Object>>> getTaskCompletionTrend(
            @Parameter(description = "天数") @RequestParam(defaultValue = "30") Integer days) {
        String userId = UserContext.requireUserId();
        List<Map<String, Object>> result = taskService.getTaskCompletionTrend(userId, days);
        return Result.success(result);
    }

    @GetMapping("/statistics/priority-distribution")
    @Operation(summary = "获取任务优先级分布", description = "获取任务优先级的分布情况")
    public Result<List<Map<String, Object>>> getTaskPriorityDistribution(
            @Parameter(description = "项目ID") @RequestParam(required = false) String projectId) {
        String userId = UserContext.requireUserId();
        List<Map<String, Object>> result = taskService.getTaskPriorityDistribution(userId, projectId);
        return Result.success(result);
    }
}
